﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using X.PagedList;
using XbsWebAPI.Application.CampRoom.Dtos;
using XbsWebAPI.Application.CampRoom.HouseType;
using XbsWebAPI.Application.CampRoom.Room.Dtos;
using XbsWebAPI.Application.QueryModel;
using XbsWebAPI.Core.Repositories;
using XbsWebAPI.EntityFrameworkCore.Entities;
using XbsWebAPI.EntityFrameworkCore.Entities.Enums;

namespace XbsWebAPI.Application
{
    public class HouseTypeAppService : IHouseTypeAppService
    {
        private readonly IHouseTypeRepository _houseTypeRepository;
        private readonly IHouseTypeHolidayRepository _houseTypeHolidayRepository;
        private readonly IHouseTypeSpecialDayRepository _houseTypeSpecialDayRepository;
        private readonly ICampRepository _campRepository;
        private readonly ISupportingFacilityRepository _supportingFacilityRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<HouseTypeAppService> _logger;
        private readonly IRoomRepository roomRepository;

        public HouseTypeAppService(IHouseTypeRepository houseTypeRepository,IMapper mapper, IHouseTypeHolidayRepository houseTypeHolidayRepository,IHouseTypeSpecialDayRepository houseTypeSpecialDayRepository, ICampRepository campRepository, ISupportingFacilityRepository supportingFacilityRepository,ILogger<HouseTypeAppService> logger,IRoomRepository roomRepository)
        {
            _houseTypeRepository = houseTypeRepository;
            _houseTypeHolidayRepository = houseTypeHolidayRepository;
            _houseTypeSpecialDayRepository = houseTypeSpecialDayRepository;
            _mapper = mapper;
            _campRepository = campRepository;
            _supportingFacilityRepository = supportingFacilityRepository;
            _logger = logger;
            this.roomRepository = roomRepository;
        }

        public Task<ResultDto<string>> CreateHouseTypeAsync(HouseType model)
        {
            var result = new ResultDto<string>();

            try
            {
                model = new HouseType()
                {
                    Id = Guid.NewGuid(),
                    Name = "测试房型2",
                    CampId = new Guid("b291a7f3-f58f-4045-8d2e-cb23ef3b1d0c"),
                    RoomArea = 20,
                    GuestNumber = 1,
                    BedType = BedType.BigBed,
                    BedSize = "",
                    HasWindow = true,
                    BreakfastCount = 2,
                    Description = "",
                    CreationDate = DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")
                };
                _houseTypeRepository.CreateAsync(model);
                result.Code = 0;
                result.Message = "";
                result.Result = "操作成功";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
            }

            return Task.FromResult(result);
        }



        public ResultDto<HouseType> GetHouseTypeById(Guid id)
        {
            var result = new ResultDto<HouseType>();

            try
            {
                var model = _houseTypeRepository.QueryById(id);
                result.Code = 0;
                result.Message = "操作成功";
                result.Result = model;
                
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = null;
                return result;
            }

            return result;
        }

        public ResultDto<PageListDto<ListHouseTypeDto>> GetHouseTypePagedList(QueryHouseType query)
        {
            var result = new ResultDto<PageListDto<ListHouseTypeDto>>();

            try
            {
                var houseTypeQuery = _houseTypeRepository.AsQueryable();

                if (!string.IsNullOrEmpty(query.Name))
                {
                    houseTypeQuery = houseTypeQuery.Where(a => a.Name.Contains(query.Name));
                }
                if (query.CampId != null)
                {
                    houseTypeQuery = houseTypeQuery.Where(a => a.CampId == query.CampId);
                }
                if (query.HouseTypeStatus != null)
                {
                    houseTypeQuery = houseTypeQuery.Where(a => a.HouseTypeStatus == query.HouseTypeStatus.Value);
                }

                houseTypeQuery = houseTypeQuery.Include(a => a.Camp).OrderByDescending(a => a.CreationDate);
                var pagedList = houseTypeQuery.ToPagedList(query.PageNumber ?? 1, query.PageSize ?? 10);

                PageListDto<ListHouseTypeDto> resultPaged = new PageListDto<ListHouseTypeDto>()
                {
                    PageNumber = pagedList.PageNumber,
                    PageSize = pagedList.PageSize,
                    HasPreviousPage = pagedList.HasPreviousPage,
                    HasNextPage = pagedList.HasNextPage,
                    TotalCount = pagedList.TotalItemCount
                };

                var dtos = pagedList.Select(e => _mapper.Map<ListHouseTypeDto>(e)).ToList();
                resultPaged.Dtos = dtos;

                result.Code = 0;
                result.Message = "操作成功";
                result.Result = resultPaged;
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = null;
                return result;
            }

            return result;
        }

        public Task<ResultDto<string>> TakeHouseTypeOnOff(Guid id, int status)
        {
            var result = new ResultDto<string>();
            try
            {
                var model = _houseTypeRepository.AsQueryable()
                    .Include(a => a.Rooms).FirstOrDefault(a => a.Id == id);
                if (model == null)
                {
                    result.Code= -1;
                    result.Message = "当前房型不存在";
                    result.Result = "操作失败";
                    _logger.LogError($"Id={id}的房型不存在，请重新操作");
                }else if((HouseTypeStatus)status == HouseTypeStatus.HasBeenOn && model.HouseTypeStatus == HouseTypeStatus.HasBeenOn)
                {
                    //执行上架操作,本身上架的，无需重复操作
                    result.Code = -1;
                    result.Message = "该房型已上架，请勿重复上架";
                    result.Result = "操作失败";
                    _logger.LogError($"Id={id}的房型该房型已上架，请勿重复上架");
                }else if(model.Rooms == null || model.Rooms.Count == 0)
                {
                    result.Code = -1;
                    result.Message = "房型必须有房间绑定才能上架";
                    result.Result = "操作失败";
                    _logger.LogError($"Id={id}房型必须有房间绑定才能上架");
                }else if(model.HighSeasonBasicPrice == 0 || model.LowSeasonBasicPrice == 0)
                {
                    result.Code = -1;
                    result.Message = "房型的淡季和旺季的基础价格必须设置，否则无法上架";
                    result.Result = "操作失败";
                    _logger.LogError($"Id={id}房型的淡季和旺季的基础价格必须设置，否则无法上架");
                }

                model.HouseTypeStatus = (HouseTypeStatus)status;
                _houseTypeRepository.Update(model);

                result.Code = 0;
                result.Message = "";
                result.Result = "操作成功";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }

        public Task<ResultDto<string>> CreateHouseTypeHolidayAsync(CreateHouseTypeHolidayDto model)
        {
            var result = new ResultDto<string>();

            try
            {
                string[] dateRange = model.DateRange.Split("-");
                var entity = _mapper.Map<HouseTypeHoliday>(model);
                entity.BeginDate = Convert.ToDateTime(dateRange[0]);
                entity.EndDate = Convert.ToDateTime(dateRange[1]);
                _houseTypeHolidayRepository.CreateAsync(entity);

                result.Code = 0;
                result.Message = "";
                result.Result = "操作成功";

            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
            }

            return Task.FromResult(result);
        }

        public ResultDto<GetHouseTypeHolidayDto> GetHouseTypeHoliday(Guid id)
        {
            var result = new ResultDto<GetHouseTypeHolidayDto>();
            try
            {
                var model = _houseTypeHolidayRepository.QueryById(id);
                var entity = _mapper.Map<GetHouseTypeHolidayDto>(model);
                entity.DateRange = model.BeginDate.Value.ToString("yyyy.MM.dd") + "-" + model.EndDate.Value.ToString("yyyy.MM.dd");
                result.Code = 0;
                result.Message = "";
                result.Result = entity;
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = null;
                return result;
            }
            return result;
        }

        public Task<ResultDto<string>> UpdateHouseTypeHolidayAsync(EditHouseTypeHolidayDto model)
        {
            var result = new ResultDto<string>();

            try
            {
                string[] dateRange = model.DateRange.Split("-");
                var entity = _mapper.Map<HouseTypeHoliday>(model);
                entity.BeginDate = Convert.ToDateTime(dateRange[0]);
                entity.EndDate = Convert.ToDateTime(dateRange[1]);
                _houseTypeHolidayRepository.UpdateAsync(entity);

                result.Code = 0;
                result.Message = "";
                result.Result = "操作成功";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }

        public ResultDto<List<ListHouseTypeHolidayDto>> GetListHouseTypeHolidays(Guid houseTypeId, SeasonStatus seasonStatus)
        {
            var result = new ResultDto<List<ListHouseTypeHolidayDto>>();
            try
            {
                var queryList = _houseTypeHolidayRepository.Query(a => a.HouseTypeId == houseTypeId && a.SeasonStatus == seasonStatus).ToList();

                var dtos = queryList.Select(e =>
                {
                    var es = _mapper.Map<ListHouseTypeHolidayDto>(e);
                    var dateRange = e.BeginDate.Value.ToString("yyyy.MM.dd") + "-" + e.EndDate.Value.ToString("yyyy.MM.dd");
                    es.DateRange = dateRange;
                    return es;
                }).ToList();

                result.Result = dtos;
                result.Code = 0;
                result.Message = "操作成功";
            }
            catch (Exception e)
            {
                result.Result = null;
                result.Code = 0;
                result.Message = e.Message;
                return result;
            }

            return result;
        }

        public Task<ResultDto<string>> RemoveHouseTypeHolidayAsync(Guid id)
        {
            var result = new ResultDto<string>();

            try
            {
                _houseTypeHolidayRepository.DeleteAsync(id);
                result.Code = 0;
                result.Message = "";
                result.Result = "操作成功";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }

        public ResultDto<GetHouseTypeSpecialDayDto> GetHouseTypeSpecialDay(Guid id)
        {
            var result = new ResultDto<GetHouseTypeSpecialDayDto>();
            try
            {
                var model = _houseTypeSpecialDayRepository.QueryById(id);
                var entity = _mapper.Map<GetHouseTypeSpecialDayDto>(model);
                entity.DateRange = model.BeginDate.Value.ToString("yyyy.MM.dd") + "-" + model.EndDate.Value.ToString("yyyy.MM.dd");
                result.Code = 0;
                result.Message = "操作成功";
                result.Result = entity;
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = null;
                return result;
            }
            return result;
        }

        public ResultDto<List<ListHouseTypeSpecialDayDto>> GetListHouseTypeSpecialDays(Guid houseTypeId, SeasonStatus seasonStatus)
        {
            var result = new ResultDto<List<ListHouseTypeSpecialDayDto>>();

            try
            {

                var queryList = _houseTypeSpecialDayRepository.Query(a => a.HouseTypeId == houseTypeId && a.SeasonStatus == seasonStatus).ToList();

                var dtos = queryList.Select(e =>
                {
                    var es = _mapper.Map<ListHouseTypeSpecialDayDto>(e);
                    var dateRange = e.BeginDate.Value.ToString("yyyy.MM.dd") + "-" + e.EndDate.Value.ToString("yyyy.MM.dd");
                    es.DateRange = dateRange;
                    return es;
                }).ToList();

                result.Code = 0;
                result.Message = "";
                result.Result = dtos;
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = null;
                return result;
            }

            return result;
        }

        public Task<ResultDto<string>> CreateHouseTypeSpecialDayAsync(CreateHouseTypeSpecialDayDto model)
        {
            var result = new ResultDto<string>();

            try
            {
                string[] dateRange = model.DateRange.Split("-");
                var entity = _mapper.Map<HouseTypeSpecialDay>(model);
                entity.BeginDate = Convert.ToDateTime(dateRange[0]);
                entity.EndDate = Convert.ToDateTime(dateRange[1]);
                _houseTypeSpecialDayRepository.CreateAsync(entity);

                result.Code = 0;
                result.Message = "操作成功";
                result.Result = "";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }

        public Task<ResultDto<string>> UpdateHouseTypeSpecialDayAsync(EditHouseTypeSpecialDayDto model)
        {
            var result = new ResultDto<string>();

            try
            {
                string[] dateRange = model.DateRange.Split("-");
                var entity = _mapper.Map<HouseTypeSpecialDay>(model);
                entity.BeginDate = Convert.ToDateTime(dateRange[0]);
                entity.EndDate = Convert.ToDateTime(dateRange[1]);
                _houseTypeSpecialDayRepository.UpdateAsync(entity);

                result.Code = 0;
                result.Message = "";
                result.Result = "操作成功";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }

        public Task<ResultDto<string>> RemoveHouseTypeSpecialDayAsync(Guid id)
        {
            var result = new ResultDto<string>();

            try
            {
                _houseTypeSpecialDayRepository.DeleteAsync(id);
                result.Code = 0;
                result.Message = "";
                result.Result = "操作成功";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }

        public ResultDto<GetHouseTypeBasicDto> GetHouseTypeBasicById(Guid id)
        {
            var result = new ResultDto<GetHouseTypeBasicDto>();

            try
            {
                var model = _houseTypeRepository.Query(a => a.Id == id)
                    .Include(a => a.HouseTypePictures)
                    .Include(a => a.Camp)
                    .Include(a => a.HouseTypeSupportingFacilities).First();
                var entity = _mapper.Map<GetHouseTypeBasicDto>(model);
                if(model.HouseTypePictures != null && model.HouseTypePictures.Count > 0)
                {
                    entity.Files = model.HouseTypePictures.Select(a => a.PicUrl).ToList();
                }
                //后面存缓存
                if (model.HouseTypeSupportingFacilities != null && model.HouseTypeSupportingFacilities.Count > 0)
                {
                    foreach(var item in model.HouseTypeSupportingFacilities)
                    {
                        var supporting = _supportingFacilityRepository.QueryById(item.SupportingFacilityId);
                        if(supporting != null)
                        {
                            //supportings.Add(item.SupportingFacilityId, supporting.Name);
                            entity.Supportings.Add(new Supporting
                            {
                                SupportingFacilityId = item.SupportingFacilityId,
                                Name = supporting.Name,
                            });
                        }
                    }
                    
                }
                entity.CampItems = _campRepository.AsQueryable().ToDictionary(key => key.Id, value => value.Name);
                result.Code = 0;
                result.Message = "操作成功";
                result.Result = entity;
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = null;

                return result;
            }

            return result;
        }

        public Task<ResultDto<Guid>> CreateHouseTypeBasicAsync(CreateHouseTypeBasicDto model)
        {
            var result = new ResultDto<Guid>();
            try
            {
                var entity = _mapper.Map<HouseType>(model);
                _houseTypeRepository.CreateInCludeImageAsync(entity,model.Files);
                result.Message = "操作成功";
                result.Result = entity.Id;
            }
            catch (Exception e)
            {
                result.Message = e.Message;
                result.Code= -1;
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }

        public Task<ResultDto<Guid>> UpdateHouseTypeBasicAsync(EditHouseTypeBasicDto model)
        {
            var result = new ResultDto<Guid>();
            try
            {
                var entity = _mapper.Map<HouseType>(model);
                _houseTypeRepository.UpdateInCludeImageAsync(entity, model.Files);
                result.Message = "操作成功";
                result.Result = entity.Id;
            }
            catch (Exception e)
            {
                result.Message = e.Message;
                result.Code = -1;
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }

        public ResultDto<HouseTypePriceDto> GetHouseTypePriceById(Guid id)
        {
            var result = new ResultDto<HouseTypePriceDto>();

            var model = _houseTypeRepository.AsQueryable()
                .Include(a => a.HouseTypeSpecialDays)
                .Include(a => a.HouseTypeHolidays)
                .FirstOrDefault(a => a.Id == id);

            if (model == null)
            {
                _logger.LogError($"ID={model.Id}的用户不存在");
                throw new Exception($"ID={model.Id}的用户不存在");
            }
            var priceModel = new HouseTypePriceDto();
            priceModel.Id = id;
            //priceModel.CampId = model.CampId;
            priceModel.LowSeasonPriceInfo = new PriceInfo
            {
                BasicPrice = model.LowSeasonBasicPrice,
                WeekendPrice = model.LowSeasonWeekendPrice ?? 0,
            };
            priceModel.HighSeasonPriceInfo = new PriceInfo
            {
                BasicPrice = model.HighSeasonBasicPrice,
                WeekendPrice = model.HightSeasonWeekendPrice ?? 0,
            };

            //组装节假日
            var lowerSeasonholidayPriceList = new List<HolidayPrice>();
            var highSeasonholidayPriceList = new List<HolidayPrice>();
            if (model.HouseTypeHolidays != null && model.HouseTypeHolidays.Any())
            {
                foreach (var item in model.HouseTypeHolidays.Where(a => a.SeasonStatus == SeasonStatus.LowSeason))
                {
                    lowerSeasonholidayPriceList.Add(new HolidayPrice
                    {
                        Name = item.Name,
                        Price = item.HolidayPrice,
                        DateRange = item.BeginDate.Value.ToString("yyyy.MM.dd") + "-" + item.EndDate.Value.ToString("yyyy.MM.dd")
                    });
                }
                foreach (var item in model.HouseTypeHolidays.Where(a => a.SeasonStatus == SeasonStatus.HighSeason))
                {
                    highSeasonholidayPriceList.Add(new HolidayPrice
                    {
                        Name = item.Name,
                        Price = item.HolidayPrice,
                        DateRange = item.BeginDate.Value.ToString("yyyy.MM.dd") + "-" + item.EndDate.Value.ToString("yyyy.MM.dd")
                    });
                }
            }

            //组装特殊日
            var lowSeasonSpecailPriceList = new List<SpecialDayPrice>();
            var highSeasonSpecailPriceList = new List<SpecialDayPrice>();
            if (model.HouseTypeSpecialDays != null && model.HouseTypeSpecialDays.Any())
            {
                foreach (var item in model.HouseTypeSpecialDays.Where(a => a.SeasonStatus == SeasonStatus.LowSeason))
                {
                    lowSeasonSpecailPriceList.Add(new SpecialDayPrice
                    {
                        Price = item.SpecialDayPrice,
                        DateRange = item.BeginDate.Value.ToString("yyyy.MM.dd") + "-" + item.EndDate.Value.ToString("yyyy.MM.dd")
                    });
                }
                foreach (var item in model.HouseTypeSpecialDays.Where(a => a.SeasonStatus == SeasonStatus.HighSeason))
                {
                    highSeasonSpecailPriceList.Add(new SpecialDayPrice
                    {
                        Price = item.SpecialDayPrice,
                        DateRange = item.BeginDate.Value.ToString("yyyy.MM.dd") + "-" + item.EndDate.Value.ToString("yyyy.MM.dd")
                    });
                }
            }

            priceModel.LowSeasonPriceInfo.SpecialDayPrices = lowSeasonSpecailPriceList;
            priceModel.LowSeasonPriceInfo.HolidayPrices = lowerSeasonholidayPriceList;
            priceModel.HighSeasonPriceInfo.SpecialDayPrices = highSeasonSpecailPriceList;
            priceModel.HighSeasonPriceInfo.HolidayPrices = highSeasonholidayPriceList;
            result.Result = priceModel;
            result.Message = "操作成功";

            return result;
        }

        public Task<ResultDto<Guid>> SetHouseTypePriceAsync(HouseTypePriceDto model)
        {
            var result = new ResultDto<Guid>();
           
            using(var ts = new TransactionScope())
            {
                try
                {
                    var original = _houseTypeRepository.QueryById(model.Id);
                    if (original == null)
                    {
                        _logger.LogError($"ID={model.Id}的用户不存在");
                        throw new Exception($"ID={model.Id}的用户不存在");
                    }

                    //删除以前节假日信息
                    var originalSpecialDays = _houseTypeSpecialDayRepository.AsQueryable().Where(a => a.HouseTypeId == model.Id).ToList();
                    if (originalSpecialDays != null && originalSpecialDays.Any())
                    {
                        foreach (var day in originalSpecialDays)
                        {
                            _houseTypeSpecialDayRepository.DeleteAsync(day.Id);
                        }

                    }

                    //删除以前特殊日信息
                    var originalHoliDays = _houseTypeHolidayRepository.AsQueryable().Where(a => a.HouseTypeId == model.Id).ToList();
                    if (originalHoliDays != null && originalHoliDays.Any())
                    {
                        foreach (var day in originalHoliDays)
                        {
                            _houseTypeHolidayRepository.DeleteAsync(day.Id);
                        }
                    }

                    //将新的特殊日信息组装 新增
                    var newSpecialDays = new List<HouseTypeSpecialDay>();
                    //1、淡季特殊日
                    if (model.LowSeasonPriceInfo.SpecialDayPrices.Count > 0)
                    {
                        foreach (var item in model.LowSeasonPriceInfo.SpecialDayPrices)
                        {
                            string[] dateRange = item.DateRange.Split("-");
                            newSpecialDays.Add(new HouseTypeSpecialDay
                            {
                                HouseTypeId = model.Id,
                                SeasonStatus = SeasonStatus.LowSeason,
                                BeginDate = Convert.ToDateTime(dateRange[0]),
                                EndDate = Convert.ToDateTime(dateRange[1]),
                                SpecialDayPrice = item.Price,
                            });
                        }
                    }

                    //2、旺季特殊日
                    if (model.HighSeasonPriceInfo.SpecialDayPrices.Count > 0)
                    {
                        foreach (var item in model.HighSeasonPriceInfo.SpecialDayPrices)
                        {
                            string[] dateRange = item.DateRange.Split("-");
                            newSpecialDays.Add(new HouseTypeSpecialDay
                            {
                                HouseTypeId = model.Id,
                                SeasonStatus = SeasonStatus.HighSeason,
                                BeginDate = Convert.ToDateTime(dateRange[0]),
                                EndDate = Convert.ToDateTime(dateRange[1]),
                                SpecialDayPrice = item.Price,
                            });
                        }
                    }


                    //将新的节假日信息组装 新增
                    var newHolidays = new List<HouseTypeHoliday>();
                    //1、淡季节假日
                    if (model.LowSeasonPriceInfo.HolidayPrices.Count > 0)
                    {
                        foreach (var item in model.LowSeasonPriceInfo.HolidayPrices)
                        {
                            string[] dateRange = item.DateRange.Split("-");
                            newHolidays.Add(new HouseTypeHoliday
                            {
                                Name = item.Name,
                                HouseTypeId = model.Id,
                                SeasonStatus = SeasonStatus.LowSeason,
                                BeginDate = Convert.ToDateTime(dateRange[0]),
                                EndDate = Convert.ToDateTime(dateRange[1]),
                                HolidayPrice = item.Price,
                            });
                        }
                    }
                    //2、旺季节假日
                    if (model.HighSeasonPriceInfo.HolidayPrices.Count > 0)
                    {
                        foreach (var item in model.HighSeasonPriceInfo.HolidayPrices)
                        {
                            string[] dateRange = item.DateRange.Split("-");
                            newHolidays.Add(new HouseTypeHoliday
                            {
                                Name = item.Name,
                                HouseTypeId = model.Id,
                                SeasonStatus = SeasonStatus.HighSeason,
                                BeginDate = Convert.ToDateTime(dateRange[0]),
                                EndDate = Convert.ToDateTime(dateRange[1]),
                                HolidayPrice = item.Price,
                            });
                        }
                    }

                    //入库
                    foreach (var item in newHolidays)
                    {
                        _houseTypeHolidayRepository.CreateAsync(item);
                    }

                    foreach (var item in newSpecialDays)
                    {
                        _houseTypeSpecialDayRepository.CreateAsync(item);
                    }

                    original.LowSeasonBasicPrice = model.LowSeasonPriceInfo.BasicPrice;
                    original.HighSeasonBasicPrice = model.HighSeasonPriceInfo.BasicPrice;
                    original.LowSeasonWeekendPrice = model.LowSeasonPriceInfo.WeekendPrice;
                    original.HightSeasonWeekendPrice = model.HighSeasonPriceInfo.WeekendPrice;
                    //original.
                    _houseTypeRepository.Update(original);
                    ts.Complete();
                }
                catch (Exception e)
                {
                    _logger.LogError($"ID={model.Id}数据异常，{e.Message}");
                    result.Message = e.Message;
                    return Task.FromResult(result);
                }
            }

            result.Result = model.Id;
            return Task.FromResult(result);
        }

        public Task<ResultDto<string>> AddBindRooms(CreateBindRoomDto model)
        {
            var result = new ResultDto<string>();
            using(var ts = new TransactionScope())
            {
                try
                {
                    //查询当前房型下是否有重名的,有重名跳过添加
                    //最开始 ABCDE
                    //后面重新绑定 CDEF
                    //CDE房间跳过不处理
                    //AB房间解绑，F房间新增

                    //当前房型下所有房间
                    var houseTypeRooms = roomRepository.Query(a => a.HouseTypeId == model.HouseTypeId).ToList();

                    foreach (var room in houseTypeRooms)
                    {
                        //1、先解绑该房型下所有的房间
                        room.HouseTypeId = null;
                        room.RoomBindingStatus = RoomBindingStatus.Unbind;
                        roomRepository.Update(room);
                    }


                    //2、遍历房间号，查询为null就是新的房间然后就添加，如果是已经添加就重新绑定
                    var roomNumbers = model.RoomNumbers;

                    foreach (var roomNumber in roomNumbers)
                    {
                        var originalRoom = roomRepository.AsQueryable().FirstOrDefault(a => a.Name == roomNumber);
                        if(originalRoom == null)
                        {
                            var room = new Room()
                            {
                                Name = roomNumber,
                                HouseTypeId = model.HouseTypeId,
                                IsEnabled = true,
                                RoomBindingStatus = RoomBindingStatus.Bingding,
                                RoomUsingStatus = RoomUsingStatus.Free
                            };
                            roomRepository.CreateAsync(room);
                        }
                        else
                        {
                            originalRoom.HouseTypeId = model.HouseTypeId;
                            originalRoom.RoomBindingStatus = RoomBindingStatus.Bingding;
                            roomRepository.Update(originalRoom);
                        }
                    }

                    ts.Complete();
                    result.Message = "操作成功";
                }
                catch (Exception e)
                {
                    result.Code = -1;
                    result.Message = e.Message;
                    _logger.LogError(e.Message);
                    result.Result = "操作失败";
                    return Task.FromResult(result);
                }
            }
            

            return Task.FromResult(result);
        }

        public ResultDto<string> CheckRoomExisted(string name, Guid houseTypeId)
        {
            var result = new ResultDto<string>();
            try
            {
                var room = roomRepository.Query(a => a.Name == name && a.HouseTypeId == houseTypeId).FirstOrDefault();
                if (room != null)
                {
                    result.Message = "房间号重名，请更换名字";
                    result.Code = -1;
                    return result;
                }

                result.Message = "当前房间名可以添加";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                _logger.LogError(e.Message);
                result.Result = "操作失败";
                return result;
            }
            return result;
        }

        public ResultDto<List<GetRoomDto>> FindRoomsByHouseTypeId(Guid id)
        {
            var result = new ResultDto<List<GetRoomDto>>();
            try
            {
                var list = roomRepository.AsQueryable().Where(a => a.HouseTypeId == id).ToList();
                var dtos = new List<GetRoomDto>();
                if (list.Count > 0)
                {
                    dtos = list.Select(e => _mapper.Map<GetRoomDto>(e)).ToList();
                }
                result.Result = dtos;
                result.Message = "操作成功";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                _logger.LogError(e.Message);
                return result;
            }
            return result;
        }

        public ResultDto<decimal> FindHouseTypeIdPriceFromDate(DateTime selectDate, Guid houseTypeId)
        {
            throw new NotImplementedException();
        }

        public Task<ResultDto<string>> RemoveHouseTypeById(Guid id)
        {
            var result = new ResultDto<string>();
            try
            {
                _houseTypeRepository.DeleteAsync(id);
                result.Message = "操作成功";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }
    }
}
